package com.javasea.account.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.codingapi.txlcn.tc.annotation.LcnTransaction;
import com.javasea.account.dao.AccountMapper;
import com.javasea.account.entity.Account;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

@Slf4j
@Service
public class AccountService {

    private static final String ERROR_USER_ID = "0";

    @Resource
    private AccountMapper accountMapper;

    @LcnTransaction
    @Transactional(rollbackFor = Exception.class)
    public void debit(String userId, Integer num) {
//        QueryWrapper<Account> wrapper = new QueryWrapper<>();
//        wrapper.setEntity(new Account().setUserId(userId));
//
//        Account account = accountMapper.selectOne(wrapper);
//
//        account.setMoney(account.getMoney() - num);
//        accountMapper.updateById(account);
//
//        // 抛出异常用于模拟服务报错进行回滚
//        if (ERROR_USER_ID.equals(userId)) {
//            throw new RuntimeException("account branch exception");
//        }

        Account entity = new Account();
        entity.setUserId("longxiaonan");
        entity.setMoney(234234234);
        accountMapper.insert(entity);
        Account account = accountMapper.selectById(entity.getId());
        account.setMoney(100101010);
        accountMapper.updateById(account);
    }
}
